extends CharacterBody2D
enum BaseState{
	IDLE,#待机
	WALK,#走
	RUN,#跑
	DEATH,#死亡
	HIT,#被击
}
@export var follow_target : Node2D
@export var random_scale : float = 10.0
@export var record_timer_rate : float = 0.5
@onready var record_timer : Timer = $RecordTimer
const MOVE_SPEED : float = 300.0
var state_anim : Dictionary
var follow_pos_array : Array[Vector2] = []#跟随阶段目标点
var is_follow : bool = false
var follow_time : float = 0.0

func _ready() -> void:
	_init_state_anim()
	record_timer.wait_time = record_timer_rate
	record_timer.timeout.connect(_on_record_time_out)

func _physics_process(_delta) -> void:
	if follow_target :
		var dis_to_target = global_position.distance_to(follow_target.global_position)
		if dis_to_target > 100.0 :
			is_follow = true
			#跟随中
			if follow_pos_array.size() > 0 :
				var first_pos = follow_pos_array[0]
				var dis_to_first_pos = global_position.distance_to(first_pos)
				if dis_to_first_pos > randf_range(random_scale-9.0,random_scale+9.0) :
					velocity = (first_pos - global_position).normalized() * MOVE_SPEED
					pass
				else :
					#到达目标点则移除目标点
					velocity = velocity / 2.0
					follow_pos_array.pop_at(0)
					follow_time = 0.0
					pass
			#跟随时间过长直接移动
			if follow_time > 3.0 :
				global_position = follow_pos_array.back()
				follow_time = 0.0
			follow_time += _delta
		else :
			#跟随范围内结束跟随
			velocity = Vector2.ZERO
			follow_pos_array.clear()
			is_follow = false
			follow_time = 0.0
			pass
	move_and_slide()

func _init_state_anim() -> void:
	for key in BaseState.keys() :
		state_anim[key] = ActorLibrary.anim[key]
	print(state_anim)

func _on_record_time_out() :
	if follow_target and is_follow:
		follow_pos_array.push_back(follow_target.global_position)
	pass

